package com.sinoglobal.ningxia.activity.interestingGame;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.shop.PurchaseGoodsActivity;
import com.sinoglobal.ningxia.beans.TurntableGainVo;
import com.sinoglobal.ningxia.beans.TurntableInfoVo;
import com.sinoglobal.ningxia.beans.TurntableResultVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.thread.LoadImgAsyncTask;
import com.sinoglobal.ningxia.thread.LoadImgAsyncTask.LoadImageAsyncTaskCallBack;
import com.sinoglobal.ningxia.utils.BitmapUtiles;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.widget.Circleview;
import com.sinoglobal.ningxia.widget.MyDialog;
import com.sinoglobal.ningxia.widget.MyDialog.MyDialogListener;

/**
 * @author sbk
 * @createdate 2014-1-10 下午1:54:44
 * @Description: 枸杞果转盘
 */
public class LuckyTurntableActivity extends AbstractActivity implements
		OnClickListener, MyDialogListener {
	Circleview claert;
	private LayoutParams parmas;
	private ImageView ivBg;
	private MyDialog myDialog;
	private RelativeLayout mLayout;
	private TurntableResultVo re;
	private int screnWidth;
	private TextView userScore, ruleTv;
	private boolean isStart = true; // true 转盘不可点击 false 可以点击进行转盘
	private boolean isBack = true; // true 可以返回 false 不可以返回上个界面
	private String gain = "";// 是否为兑换
	// private boolean exchangeFlag=false;//积分兑换机会

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.turntable_layout);
		templateButtonRight.setText(getString(R.string.mycoupons));
		templateButtonRight
				.setBackgroundResource(R.drawable.bg_mallshop_mycoupons);
		templateButtonRight
				.setTextColor(getResources().getColor(R.color.white));
		titleView.setText(getString(R.string.lucky_turntable));
		userScore = (TextView) findViewById(R.id.title_right_score);
		ruleTv = (TextView) findViewById(R.id.tur_rule_info);
		templateButtonRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) { // 我的
				if (isLoginIntentLoginActivity()) {
					Intent intent = new Intent(LuckyTurntableActivity.this,
							MyPrizeActivity.class);
					startActivity(intent);
				}
			}
		});
		mLayout = (RelativeLayout) findViewById(R.id.Lottery);
		ivBg = (ImageView) findViewById(R.id.iv1);
		ivBg.setImageBitmap(BitmapUtiles.scaleBitmapforWidth(BitmapFactory
				.decodeResource(getResources(), R.drawable.zhunpan_df_img),
				FlyApplication.widthPixels));
		screnWidth = FlyApplication.widthPixels;

		claert = new Circleview(this, screnWidth, mhandler);
		// LayoutParams parmas=(LayoutParams) layout.getLayoutParams();
		// claert.set
		// claert = (Circleview) findViewById(R.id.myCircle);
		parmas = new LayoutParams(LayoutParams.MATCH_PARENT,
				EquipmentUtil.dip2px(this, 300));
		parmas.addRule(RelativeLayout.CENTER_IN_PARENT);
		mLayout.addView(claert, parmas);
		// claert.setOnClickListener(this);
		mLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (!isStart) {
					touchIsCenter(event);
				}

				return false;
			}
		});
		loadDataInfo();
	}

	/**
	 * 添加随机数，制定奖项数量为上限，一般抽奖中什么都是服务器返回的，可以在请求服务器接口成功在制定转盘转到那个奖项
	 */
	private Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				complete();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * @author sbk
	 * @createdate 2014-1-14 下午1:46:59
	 * @Description: 取得奖品信息
	 */
	private void loadDataInfo() {
		new ItktAsyncTaskWithDialog<Void, Void, TurntableInfoVo>(getString(R.string.loading_prize_info),
				true, false) {
			@Override
			public TurntableInfoVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getTurntableInfo(); // 2代表android
			}

			@Override
			public void after(TurntableInfoVo result) {
				if (Code.CODE_SUCCESS != result.getCode()) {
					userScore.setText(MContants.EMPTY_STRING == result.getScore() ?getString(R.string.medlar_total_nums)+ "0"
							: getString(R.string.medlar_total_nums) + result.getScore());
					showShortToastMessage(result.getMessage());
					return;
				}
				LoadImg(result);
				userScore.setText(MContants.EMPTY_STRING == result.getScore() ? getString(R.string.medlar_total_nums)+"0"
						: getString(R.string.medlar_total_nums)+ result.getScore());
				ruleTv.setText(result.getRule());
			}

			@Override
			public void exception() {
				dismissWaitingDialog();
				showShortToastMessage(getString(R.string.loading_failed));
			}
		}.execute();
	}

	private void LoadImg(TurntableInfoVo result) {
		new LoadImgAsyncTask(new LoadImageAsyncTaskCallBack() {
			@Override
			public void beforeLoadImage() {
				ivBg.setImageBitmap(BitmapUtiles.scaleBitmapforWidth(
						BitmapFactory.decodeResource(getResources(),
								R.drawable.zhunpan_df_img),
						FlyApplication.widthPixels));
			}

			@Override
			public void afterLoadImage(Bitmap bitmap) {
				// 对下载下来的图片进行处理
				if (bitmap != null) {
					ivBg.setImageBitmap(BitmapUtiles.scaleBitmapforWidth(
							bitmap, FlyApplication.widthPixels));
					isStart = false;
				}
			}
		}).execute(ConnectionUtil.localUrl + result.getAndr_lbimg());
	}

	/**
	 * @author sbk
	 * @createdate 2014-1-17 下午2:07:28
	 * @Description: (用一句话描述该方法做什么)
	 * @param zhong
	 *            () 1、枸杞果；2、未中奖；3、实物
	 */
	private void showDialog(TurntableResultVo re) {
		if (myDialog == null) {
			myDialog = new MyDialog(this);
		}
		//myTask 中文与对话框优化
		if (3 == re.getCode()) {
			myDialog.tvTitle.setText("啊哦！");
			myDialog.tvMessage.setText("您今天的抽奖机会已经用完，花" + re.getDeduct_score()
					+ "积分可兑换一次抽奖机会，要试试吗？");
			myDialog.btnPositive.setText("试一试");
			myDialog.btnNegative.setVisibility(View.VISIBLE);
			myDialog.btnPositive.setVisibility(View.VISIBLE);
			myDialog.btnNegative.setText("算了");
		} else if ("3".equals(re.getJson().getZhong())) {
			myDialog.btnNegative.setVisibility(View.GONE);
			myDialog.btnPositive.setVisibility(View.VISIBLE);
			myDialog.tvTitle.setText("恭喜您获得");
			myDialog.tvMessage.setText(re.getJson().getPrize_name() + ",请于"
					+ re.getJson().getLimittime() + "天内领取");
			myDialog.btnPositive.setText(getString(R.string.dialog_ok));
		} else if ("2".equals(re.getJson().getZhong())) {
			myDialog.btnNegative.setVisibility(View.GONE);
			myDialog.btnPositive.setVisibility(View.VISIBLE);
			myDialog.tvTitle.setText(getString(R.string.so_pity));
			myDialog.tvMessage.setText("没中奖，下次再努力吧~");
			myDialog.btnPositive.setText(getString(R.string.dialog_ok));
		} else {
			myDialog.btnNegative.setVisibility(View.GONE);
			myDialog.btnPositive.setVisibility(View.VISIBLE);
			myDialog.tvTitle.setText("恭喜您！");
			myDialog.tvMessage.setText("获得 " + re.getJson().getGqg() + "积分");
			myDialog.btnPositive.setText(getString(R.string.dialog_ok));
		}
		if (!myDialog.isShowing()) {
			myDialog.show();
		}
	}

	// 判断点击位置是否为屏幕的中心区域
	private boolean touchIsCenter(MotionEvent e) {
		int xBegin = screnWidth / 3;
		int xEnd = screnWidth / 3 * 2;
		int yBegin = mLayout.getHeight() / 3;
		int yEnd = mLayout.getHeight() / 3 * 2;
		System.out.println("xBegin=" + xBegin + "  xEnd=" + xEnd + "  yBegin"
				+ yBegin + "  yEnd=" + yEnd);
		if (e.getX() > xBegin && e.getX() < xEnd && e.getY() > yBegin
				&& e.getY() < yEnd) {
			isStart = true;
			loadDataResult();
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		// int place = random.nextInt(7);
	}

	/**
	 * @author sbk
	 * @createdate 2014-1-14 下午1:46:24
	 * @Description: 取得获奖结果信息
	 * 
	 */
	private void loadDataResult() {
		new ItktAsyncTaskWithDialog<Void, Void, TurntableResultVo>(getString(R.string.turn_starting),
				true, false) {

			@Override
			public TurntableResultVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getTurntableResult(gain);
			}

			@Override
			public void after(TurntableResultVo result) {
				isStart = false;
				gain = "";
				if (3 == result.getCode()) { // 超过次数
					re = result;
					showDialog(result);
					return;
				} else if (Code.CODE_SUCCESS != result.getCode()) {
					showShortToastMessage(result.getMessage());
					return;
				}
				re = result;
				claert.setStopPlace(Integer.parseInt(result.getJson()
						.getDengji()));
				claert.setStopRoter(false);
				isBack = false;

			}

			@Override
			public void exception() {
				dismissWaitingDialog();
				showShortToastMessage(getString(R.string.loading_failed));
				isStart = false;
			}
		}.execute();
	}

	private void complete() {
		try {
			isStart = false;
			isBack = true;
			showDialog(re);
		} catch (Exception e) {
		}
	}

	@Override
	public void doPositive() {
		if (myDialog != null && myDialog.isShowing()) {
			myDialog.cancel();
			if (3 == re.getCode()) { // 兑换机会
				exchange();

			} else if ("3".equals(re.getJson().getZhong())) { // 实物F
				Intent intent = new Intent(this, PurchaseGoodsActivity.class);
				intent.putExtra("goods_id", re.getJson().getPrize_id());// 商品的id
				intent.putExtra("type", "3");// 1现金 ,2枸杞果
				intent.putExtra("type2", "1");// 1实物, 2活动
				intent.putExtra("goods_id", re.getJson().getPrizemessageid());
				startActivity(intent);
			} else {
				myDialog.dismiss();
				userScore.setText(MContants.EMPTY_STRING == re.getScore() ? getString(R.string.medlar_total_nums)+"0"
						: getString(R.string.medlar_total_nums) + re.getScore());
			}
		}
	}

	/**
	 * 
	 * @author sbk
	 * @createdate 2014-7-29 上午10:08:30
	 * @Description:兑换抽奖机会
	 * 
	 */
	private void exchange() {
		new ItktAsyncTaskWithDialog<Void, Void, TurntableGainVo>() {

			@Override
			public TurntableGainVo before(Void... params) throws Exception {
				// Auto-generated method stub
				return RemoteImpl.getInstance().getTurntableTimes();
			}

			@Override
			public void after(TurntableGainVo result) {
				if (Code.CODE_SUCCESS != result.getCode()) {
					showShortToastMessage(result.getMessage());
					return;
				}
				userScore.setText(MContants.EMPTY_STRING == result.getScore() ? getString(R.string.medlar_total_nums)+"0"
						: getString(R.string.medlar_total_nums)+ result.getScore());
				gain = result.getGain();
				isStart = true;
				loadDataResult();

			}

			@Override
			public void exception() {
				// Auto-generated method stub

			}
		}.execute();

	}

	@Override
	public void doNegative() {
		myDialog.dismiss();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		if (isBack) {
			finish();
		}
	}
}
